package mongo

import (
	"gopkg.in/mgo.v2"
)

var (
	conn string
	sess *mgo.Session
)

func session() *mgo.Session {
	if sess == nil {
		var err error
		if sess, err = mgo.Dial(conn); err != nil {
			panic(err)
		}
	}
	return sess.Clone()
}

func InitMongo(connStr string) {
	conn = connStr
	session()
}

func DO(db, col string, f func(*mgo.Collection) error) error {
	s := session()
	defer func() {
		s.Close()
	}()

	return f(s.DB(db).C(col))
}

/*
func (this *Mongo) FindOne(selector bson.M, content interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(selector).One(content)
	})
}

func (this *Mongo) SelectOne(query, selector bson.M, content interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(query).One(selector)
	})
}

func (this *Mongo) FindAll(selector bson.M, out interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(selector).All(out)
	})
}

func (this *Mongo) FindAllWithLimit(selector bson.M, count int, out interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(selector).Limit(count).All(out)
	})
}

func (this *Mongo) FindAllWithLimitSort(selector bson.M, count int, out interface{}, sort string) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(selector).Sort(sort).Limit(count).All(out)
	})
}

func (this *Mongo) SelectAll(query, selector bson.M, out interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Find(query).Select(selector).All(out)
	})
}

func (this *Mongo) Create(content interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Insert(content)
	})
}

func (this *Mongo) Delete(selector bson.M) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		_, err = c.RemoveAll(selector)
		return
	})
}

func (this *Mongo) Update(selector bson.M, content interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		return c.Update(selector, content)
	})
}

func (this *Mongo) Upsert(selector bson.M, content interface{}) error {
	return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
		_, err = c.Upsert(selector, content)
		return err
	})
}

func (this *Mongo) BulkInsert(docs []interface{}) error {

		return DO(this.Db, this.Col, func(c *mgo.Collection) (err error) {
			bulk := c.Bulk()
			for _, doc := range docs {
				bulk.Insert(doc)
			}
			_, err = bulk.Run()
			return err
		})

	return nil
}*/
